import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.ExcelUtils;
import com.yt.common.utils.StrUtils;
import com.yt.common.utils.TableStructureExportUtils;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.yt.phone.models.service.IVirtualphoneService;
import com.yt.phone.models.bo.VirtualphoneSaveBO;
import com.yt.phone.models.bo.VirtualphoneBO;
import com.yt.phone.models.dto.VirtualphoneDTO;

/**
 * 虚拟电话号码信息控制器
 *
 * @author lizicong
 * @Date 2025-10-27 10:13:37
 */

@RestController
@RequestMapping("/cms/virtualphone")
@Slf4j
@Api(value = "VirtualphoneController",tags = "虚拟电话号码信息接口")
public class VirtualphoneController {

    @DubboReference
    private IVirtualphoneService virtualphoneService;
    
    @Autowired
    private TableStructureExportUtils tableStructureExportUtils;

    @ApiOperation(value = "添加虚拟电话号码信息",notes = "添加虚拟电话号码信息")
    @PostMapping(value = "/insert")
    public Result insert(VirtualphoneSaveBO saveBO) {
        boolean flag = virtualphoneService.add(saveBO);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存虚拟电话号码信息",notes = "保存虚拟电话号码信息")
    public Result save(VirtualphoneSaveBO saveBO){
        if(saveBO.getVirtualphoneId() == null){
            //添加
            return  insert(saveBO);
        } else {
            return  update(saveBO);
        }
    }

    @ApiOperation(value = "修改虚拟电话号码信息",notes = "修改虚拟电话号码信息")
    @PostMapping("/update")
    public Result update(@RequestBody VirtualphoneSaveBO saveBO){
        VirtualphoneDTO dto = new VirtualphoneDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(saveBO.getVirtualphoneId());
        boolean flag = virtualphoneService.updateById(dto);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @PostMapping("/updateStatus")
    @ApiOperation(value = "修改状态",notes = "修改状态")
     @ApiImplicitParams({
             @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
             ,@ApiImplicitParam(name = "status",value = "状态0停用，1启用",required = true,paramType = "query", dataType = "Integer")
     })
     public Result updateStatus(Long id, Integer status){
         VirtualphoneDTO dto = new VirtualphoneDTO();
         dto.setId(id);
         dto.setStatus(status);
        boolean flag = virtualphoneService.updateById(dto);
         if(flag){
             return new Result<>();
         } else {
             return new Result<>(CodeEnum.FAIL_100008);
         }
     }

    @ApiOperation(value = "删除虚拟电话号码信息",notes = "删除虚拟电话号码信息")
    @ApiImplicitParam(name = "id",value = "虚拟电话号码信息id",required = true,paramType = "query",dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id){
        boolean flag = virtualphoneService.deleteById(id);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除虚拟电话号码信息",notes = "批量删除虚拟电话号码信息")
    @ApiImplicitParam(name = "ids",value = "ids:以逗号隔开",required = true,paramType = "query", dataType = "String")
    public Result deleteBatch(@RequestParam("ids") String ids){
        if(StrUtils.isEmpty(ids)){
            return new Result(CodeEnum.FAIL_100002 );
        }
        String[] arr = ids.split(",");
        virtualphoneService.deleteBatchIds(Arrays.asList(arr));
        return new Result<>();
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<VirtualphoneDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        VirtualphoneDTO dto = virtualphoneService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "虚拟电话号码信息列表",notes = "虚拟电话号码信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<VirtualphoneDTO>> queryPageList(VirtualphoneBO bo){
        Wrapper<VirtualphoneDTO> wrapper = new EntityWrapper<>();

                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }

        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<VirtualphoneDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = virtualphoneService.selectPage(page, wrapper);

        return new Result<>(page);
    }
    
    @ApiOperation(value = "导出虚拟电话号码Excel模板", notes = "导出虚拟电话号码Excel模板")
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        try {
            // 使用ExcelUtils导出模板，确保创建表头
            List<VirtualphoneSaveBO> list = new ArrayList<>();
            ExcelUtils.exportExcel(list, "虚拟电话号码信息模板", "虚拟电话号码信息", VirtualphoneSaveBO.class, "虚拟电话号码信息模板.xls", true, response);
        } catch (Exception e) {
            log.error("导出虚拟电话号码Excel模板失败", e);
            try {
                // 如果ExcelUtils导出失败，尝试使用简单的方法创建Excel文件
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("虚拟电话号码信息模板.xls", "utf-8"));
                
                // 创建简单的Excel文件
                org.apache.poi.hssf.usermodel.HSSFWorkbook workbook = new org.apache.poi.hssf.usermodel.HSSFWorkbook();
                org.apache.poi.hssf.usermodel.HSSFSheet sheet = workbook.createSheet("虚拟电话号码信息");
                
                // 创建表头
                org.apache.poi.hssf.usermodel.HSSFRow row = sheet.createRow(0);
                row.createCell(0).setCellValue("虚拟电话id");
                row.createCell(1).setCellValue("虚拟电话号码");
                row.createCell(2).setCellValue("电话地址");
                row.createCell(3).setCellValue("价格/分钟");
                row.createCell(4).setCellValue("状态0停用，1启用");
                row.createCell(5).setCellValue("服务商");
                
                workbook.write(response.getOutputStream());
                workbook.close();
                response.flushBuffer();
            } catch (Exception ex) {
                log.error("创建简单Excel文件失败", ex);
                try {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/plain");
                    response.getWriter().write("导出Excel文件失败: " + e.getMessage() + "; " + ex.getMessage());
                } catch (Exception exc) {
                    log.error("设置错误响应失败", exc);
                }
            }
        }
    }
    
    @ApiOperation(value = "导出虚拟电话号码表结构信息", notes = "导出虚拟电话号码表结构信息")
    @PostMapping("/exportTableStructure")
    public void exportTableStructure(HttpServletResponse response) {
        try {
            // 导出虚拟电话号码表结构信息
            tableStructureExportUtils.exportTableStructureToExcel("virtualphone", response);
        } catch (Exception e) {
            log.error("导出虚拟电话号码表结构信息失败", e);
            // 设置错误响应
            try {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/plain");
                response.getWriter().write("导出表结构信息失败: " + e.getMessage());
            } catch (Exception ex) {
                log.error("设置错误响应失败", ex);
            }
        }
    }
}